express框架简单使用

express

切换不同的路由,就进入不同的逻辑,
也就是浏览器输入不同路径,页面就有不同的返回结果

1
2
3
4
5
6
7
8
9
10
11
12
13
var express = require('express')
var app = express()

app.get('/', function (req, res) {
res.send('Hello World')
})

app.get('/home', function (req, res) {
res.send('home页面')
})

app.listen(3000)
// “/”后是不同的页面不同的路由,(index.php,login.php ....)

express的脚手架

全局安装

1
2
npm install -g express-generator@4
//npm init 生成package.json文件 安装时候-S--dev保存安装依赖

在一个文件夹里面用express命令创建应用架构

1
2
express test
cd test

进入test文件夹安装依赖,推荐cnpm安装所有依赖

1
npm install

启动应用

1
2
SET DEBUG=test:*
npm start

访问在浏览器3000端口号

1
http://localhost:3000

创建路由

进入到test目录的routes文件夹,然后复制users.js

你可以改变/home这里的路径

1
2
3
4
5
6
var express = require('express');
var router = express.Router();
router.get('/home', function(req, res, next) {
res.send('hello world');
});
module.exports = router;

app.js添加以下两条,该路由就完成了

1
2
3
4
5
6
var homeRouter = require('./routes/home');
//code
app.use('/test', homeRouter);
此处第二个参数需要和命名一致
“/test”为虚拟路径
访问方法: http://localhost:3000/test/home

访问该路径

1
http://localhost:3000/test/home

mysql

连接数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//select * from students where username = 
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'lemon',
password: '123456',
database: '1806'
});
connection.query('INSERT INTO students SET ?', [{
username: req.body.username,
password: req.body.password
}], function(error, results, fields) {
if(error) throw error;
res.send("success");
});
connection.end();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//封装上述代码
//db.js
var mysql = require('mysql');//引入模块
var config = require("./config.js")

function query(sql, params, callback) {
var connection = mysql.createConnection({
host: config.host,
user: config.user,
password: config.password,
database: config.database
});
connection.connect();
connection.query(sql, params, function(error, results, fields) {
if(error) throw error;
callback(results);
connection.end();
});
}

module.exports = {
query: query
}

//config.js 文件夹下

module.exports = {
host: 'localhost',
user: 'lemon',
password: '123456',
database: '1806'
}
//用法
var db = require("./db.js");
console.log(db)
db.query("SELECT * FROM students where ?",[{
username:'qq'
}],function(data){
console.log(data)
})

=====================================================================

var db = require("./db.js");
console.log(db)
db.query("SELECT * FROM students",[],function(data){
console.log(data)
})